#include "bridgemessage.hxx"
#include <string.h>

tBridgeMsg* CreateBMsg(void)
{
	return new tBridgeMsg();
}
void ReleaseBMsg(tBridgeMsg* pmsg)
{
	if(pmsg == NULL)
		return;

	if ((pmsg)->isReceived)
		delete[] ((pmsg)->msg);	// creation : (*appmsg)->msg = new tByte[msg_length];
	else
		was_free_msg((void**)(&(pmsg)->msg));

	delete pmsg;
	pmsg=NULL;
}
tBridgeMsg* DupBMsg(const tBridgeMsg* msg)
{
	if (!msg)
		return 0;

	tBridgeMsg* new_msg = CreateBMsg();

	new_msg->rhost = msg->rhost;
	new_msg->rport = msg->rport;

	new_msg->lom = msg->lom;
	new_msg->mpi = msg->mpi;
	new_msg->rspc = msg->rspc;
	new_msg->tid = msg->tid;
	new_msg->tom = msg->tom;

	new_msg->msg = (tByte*)malloc(sizeof(tByte) * msg->lom);
	memcpy(new_msg->msg, msg->msg, sizeof(tByte) *  msg->lom);

	new_msg->isReceived = FALSE;

	return new_msg;
}
string tagBridgeMsg::GetData(E_WAS_TAG_ID tag_id) const
{
	E_WAS_TAG_ID tmp_tag_id = E_WAS_TAG_ID_NONE;
	S_WAS_TAG_DATA p_td;

	memset(&p_td, 0x00, sizeof(S_WAS_TAG_DATA));

	while (E_WAS_TAG_ID_NONE != (tmp_tag_id=was_get_next_tag_data(msg, lom, &p_td)))
	{
		if (tmp_tag_id==tag_id)
		{
			break;
		}
	}

	if (tmp_tag_id==E_WAS_TAG_ID_NONE)
	{
		return "";
	}
	tChar* data = data=(tChar*)malloc((1+p_td.data.bs.byte_stream_len));
	memset(data, 0x00, p_td.data.bs.byte_stream_len+1);
	memcpy(data, p_td.data.bs.byte_stream, p_td.data.bs.byte_stream_len);

	string res(data);
	free(data);

	return res;
}
tUInt32 GetATid(void)
{
	static const tUInt32 TID_TOP=10000000;
	static const tUInt32 TID_BOTTOM=0;
	static tUInt32 tid_counter=TID_BOTTOM;

	if (tid_counter>TID_TOP)
		tid_counter=TID_BOTTOM;

	return ++tid_counter;
}
tUInt32 GetAMpi(void)
{
	static const tUInt32 MPI_TOP=10000000;
	static const tUInt32 MPI_BOTTOM=0;
	static tUInt32 mpi_counter=MPI_BOTTOM;

	if (mpi_counter>MPI_TOP)
		mpi_counter=MPI_BOTTOM;

	return ++mpi_counter;
}
